package com.suxin.datahub.core.reader;

import com.suxin.datahub.database.DataBaseFactory;
import com.suxin.datahub.domain.DataSourceDomain;
import com.suxin.datahub.util.JdbcUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Classname AbstractReader
 * @Description [ AbstractReader ]
 * @Author Tang
 * @Date 2020/11/11 13:12
 * @Created by ASUS
 */
public abstract class AbstractBaseReader implements Reader{

    public Connection connection = null;

    private DataSourceDomain dataSourceDomain;

    public AbstractBaseReader(DataSourceDomain dataSourceDomain) {

        this.connection = DataBaseFactory.getDataSource(dataSourceDomain);

        this.dataSourceDomain = dataSourceDomain;
    }

    @Override
    public List<Map<String, Object>> readData() {
        ResultSet resultSet = JdbcUtils.executeQuery(
                this.dataSourceDomain.getSql(),
                this.connection,
                null
        );
        List<Map<String, Object>> datas = new ArrayList<>();
        try {
            assert resultSet != null;
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            List<String> columns = new ArrayList<>(10);
            // 获取所有的列
            for (int i = 0; i < columnCount; i++) {
                columns.add(metaData.getColumnName(i + 1));
            }
            while (resultSet.next()) {
                Map<String, Object> map = new HashMap<>(16);
                // 取出每一列放入map
                columns.forEach((item) -> {
                    try {
                        map.put(item,resultSet.getObject(item));
                    } catch (SQLException throwables) {
                        throwables.printStackTrace();
                    }
                });
                datas.add(map);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return datas;
    }
}